var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var HttpClient = (function () {
            function HttpClient(url) {
                this._url = "";
                this._session_id = "";
                this._url = url;
            }
            HttpClient.prototype.connect = function (ip, game) {
                return true;
            };
            HttpClient.prototype.disconnect = function () {
                return true;
            };
            HttpClient.prototype._isEmpty = function (obj) {
                if (typeof obj == "undefined" || obj == null || obj == "") {
                    return true;
                }
                else {
                    return false;
                }
            };
            HttpClient.prototype.__sendMsg = function (msg) {
                var bytes = HttpClient.NULL_BYTES;
                var _data = client.TObject.newInstance();
                _data.putString(HttpClient._Session, this._session_id);
                _data.putInt(HttpClient._Version, client.NetManager.VERSION);
                if (msg.useText && msg.param == null) {
                    if (this._isEmpty(msg.textParam)) {
                        msg.param = client.TObject.newInstance();
                    }
                    else {
                        try {
                            msg.param = client.TObject.newFromJson(msg.textParam);
                        }
                        catch (e) {
                            msg.param = client.TObject.newInstance();
                        }
                    }
                }
                _data.putTObject(HttpClient._Param, msg.param);
                var buff = _data.toBinary();
                try {
                    buff.compress();
                }
                catch (e) {
                    client.log.error(e);
                }
                bytes = buff.bytes;
                this.__requestAsync(msg, bytes);
            };
            HttpClient.prototype.__response = function (code, msg) {
                if (msg.callback != null) {
                    var response = new client.MessageResponse();
                    response.messageData = msg;
                    response.returnCode = code;
                    msg.callback(response);
                }
            };
            HttpClient.prototype.__requestAsync = function (msg, bytes) {
                var self = this;
                var xhs = new XMLHttpRequest();
                xhs.timeout = client.NetManager.TIMEOUT_TIME * 1000;
                xhs.open(HttpClient._Method, this._url + msg.command, true);
                xhs.ontimeout = function (evt) {
                    self.__response(102, msg);
                };
                xhs.onerror = function (evt) {
                    self.__response(101, msg);
                };
                xhs.onload = function (evt) {
                    var code = 500;
                    if (xhs.readyState == 4 && xhs.status == 200) {
                        var _data = xhs.response;
                        if (_data) {
                            var bytes_1 = new client.ByteArray(_data);
                            bytes_1.uncompress();
                            var tem = client.TObject.newFromBinaryData(bytes_1);
                            var result = tem.getInt(HttpClient._Result);
                            if (result == 0) {
                                var _param = tem.getTObject(HttpClient._Param);
                                msg.param = _param;
                                if (msg.useText) {
                                    msg.textParam = _param.toJson();
                                }
                            }
                            code = result;
                        }
                    }
                    self.__response(code, msg);
                };
                xhs.responseType = "arraybuffer";
                xhs.send(bytes);
            };
            HttpClient.prototype.write = function (msg) {
                this.__sendMsg(msg);
            };
            HttpClient.prototype.getProtocol = function () {
                return client.ConnectionProtocol.Web;
            };
            HttpClient.prototype.setOnConnect = function (onConnect, thisObject) {
            };
            HttpClient.prototype.setOnEvent = function (onEvent, thisObject) {
            };
            HttpClient.prototype.getAveragePingTime = function () {
                return 100;
            };
            HttpClient.prototype.getSession = function () {
                return this._session_id;
            };
            HttpClient.prototype.setSession = function (session) {
                this._session_id = session;
            };
            HttpClient._Method = "POST";
            HttpClient.NULL_BYTES = new Uint8Array(0);
            HttpClient._Result = "$r";
            HttpClient._Param = "$p";
            HttpClient._Session = "$s";
            HttpClient._Version = "$v";
            return HttpClient;
        }());
        client.HttpClient = HttpClient;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var Message = (function () {
            function Message() {
                this.thisObject = null;
                this.callback = null;
            }
            return Message;
        }());
        client.Message = Message;
        var MessageResponse = (function () {
            function MessageResponse() {
            }
            return MessageResponse;
        }());
        client.MessageResponse = MessageResponse;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var NetManager = (function () {
            function NetManager() {
            }
            NetManager.addNetClient = function (net) {
                if (net == null) {
                    throw "TaurusClient is null, it can't be added.";
                }
                if (NetManager._clientMap[net.getId()]) {
                    throw "A client with id: " + net.getId() + " already exists! Controller can't be added: " + net;
                }
                this._clientMap[net.getId()] = net;
                this._clientList.push(net);
            };
            NetManager.getNetClient = function (id) {
                for (var i = 0; i < this._clientList.length; ++i) {
                    var nc = this._clientList[i];
                    if (nc.getId() == id)
                        return nc;
                }
                return null;
            };
            NetManager.killConnection = function (id) {
                for (var i = 0; i < this._clientList.length; ++i) {
                    var nc = this._clientList[i];
                    if (nc.getId() == id) {
                        nc.killConnection();
                        delete this._clientMap[id];
                        this._clientList.splice(i, 1);
                        break;
                    }
                }
            };
            NetManager.killAllConnection = function () {
                for (var _i = 0, _a = this._clientList; _i < _a.length; _i++) {
                    var nc = _a[_i];
                    nc.killConnection();
                }
                this._clientList = [];
                this._clientMap = {};
            };
            NetManager.TIMEOUT_TIME = 10;
            NetManager.VERSION = 10;
            NetManager.debug_print = true;
            NetManager._clientMap = {};
            NetManager._clientList = [];
            return NetManager;
        }());
        client.NetManager = NetManager;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var SocketCode;
        (function (SocketCode) {
            SocketCode[SocketCode["Connect"] = 0] = "Connect";
            SocketCode[SocketCode["Disconnect"] = 1] = "Disconnect";
            SocketCode[SocketCode["Exception"] = 2] = "Exception";
            SocketCode[SocketCode["ExceptionOnConnect"] = 3] = "ExceptionOnConnect";
            SocketCode[SocketCode["SendError"] = 4] = "SendError";
            SocketCode[SocketCode["ExceptionOnReceive"] = 5] = "ExceptionOnReceive";
            SocketCode[SocketCode["TimeoutDisconnect"] = 6] = "TimeoutDisconnect";
            SocketCode[SocketCode["DisconnectByServer"] = 7] = "DisconnectByServer";
        })(SocketCode = client.SocketCode || (client.SocketCode = {}));
        var ConnectionProtocol;
        (function (ConnectionProtocol) {
            ConnectionProtocol[ConnectionProtocol["WebSocket"] = 0] = "WebSocket";
            ConnectionProtocol[ConnectionProtocol["Web"] = 1] = "Web";
        })(ConnectionProtocol = client.ConnectionProtocol || (client.ConnectionProtocol = {}));
        var NetClientEvent = (function () {
            function NetClientEvent() {
            }
            NetClientEvent.Connect = "connect";
            NetClientEvent.OnEvent = "onevent";
            return NetClientEvent;
        }());
        client.NetClientEvent = NetClientEvent;
        var TaurusClient = (function () {
            function TaurusClient(host, game, protocol, secure) {
                if (protocol === void 0) { protocol = ConnectionProtocol.WebSocket; }
                if (secure === void 0) { secure = false; }
                this._isKill = false;
                switch (protocol) {
                    case ConnectionProtocol.WebSocket:
                        this._scoket = new client.SocketEngine(secure);
                        break;
                    case ConnectionProtocol.Web:
                        this._scoket = new client.HttpClient(host);
                        this._connect = true;
                        break;
                }
                this.__initialize(host, game);
            }
            TaurusClient._getValidID = function () {
                return ++TaurusClient._tempID;
            };
            TaurusClient.prototype.__initialize = function (host, game) {
                this._currentIp = host;
                this._gameId = game;
                this._id = TaurusClient._getValidID();
                this._dispatcher = new client.EventDispatcher();
                this._responseMap = {};
                client.NetManager.addNetClient(this);
                this._scoket.setOnConnect(function (code) {
                    if (code == SocketCode.Connect)
                        this._connect = true;
                    else
                        this._connect = false;
                    var evt = new client.Event(NetClientEvent.Connect);
                    evt.setParameter("code", code);
                    this._dispatcher.dispatchEvent(evt);
                }, this);
                this._scoket.setOnEvent(function (msg) {
                    if (this._connect) {
                        var evt = new client.Event(NetClientEvent.OnEvent);
                        evt.setParameter("msg", msg);
                        this._dispatcher.dispatchEvent(evt);
                        if (client.NetManager.debug_print) {
                            var str = this.getProtocol() == ConnectionProtocol.Web ? "WEB" : "WEBSOCKET";
                            var data_str = msg.useText ? msg.textParam : (msg.param != null ? msg.param.toJson() : "null");
                            client.log.debug("Event [" + str + "->" + msg.command + "] data:" + data_str);
                        }
                    }
                }, this);
            };
            TaurusClient.prototype.addEventListener = function (eventType, listener, thisObject) {
                this._dispatcher.addEventListener(eventType, listener, thisObject);
            };
            TaurusClient.prototype.removeAllListener = function () {
                this._dispatcher.removeAllListener();
            };
            TaurusClient.prototype.removeEventListener = function (eventType, listener, thisObject) {
                this._dispatcher.removeEventListener(eventType, listener, thisObject);
            };
            TaurusClient.prototype.connect = function () {
                this._scoket.connect(this._currentIp, this._gameId);
            };
            TaurusClient.prototype.killConnection = function () {
                this.removeAllListener();
                this._responseMap = {};
                this._scoket.disconnect();
                this._connect = false;
                this._isKill = true;
            };
            TaurusClient.prototype._send = function (msg) {
                if (msg == null)
                    return;
                if (client.NetManager.debug_print) {
                    var str = this.getProtocol() == ConnectionProtocol.Web ? "WEB" : "WEBSOCKET";
                    var data_str = msg.useText ? msg.textParam : (msg.param != null ? msg.param.toJson() : "null");
                    str = "Requst [" + str + "->" + msg.command + "] ->param:" + data_str;
                    client.log.debug(str);
                }
                if (msg.callback != null) {
                    this._responseMap[msg] = msg.callback;
                    var self = this;
                    msg.callback = function (res) {
                        var callback = self._responseMap[res.messageData];
                        delete self._responseMap[res.messageData];
                        if (client.NetManager.debug_print) {
                            var str = self.getProtocol() == ConnectionProtocol.Web ? "WEB" : "WEBSOCKET";
                            var data_str = msg.useText ? msg.textParam : (msg.param != null ? msg.param.toJson() : "null");
                            str = "Response [" + str + "->" + msg.command + "] ->result:" + res.returnCode + " param:" + data_str;
                            client.log.debug(str);
                        }
                        callback.call(res.messageData.thisObject, res);
                    };
                }
                this.sendData(msg);
            };
            TaurusClient.prototype.send = function (cmd, param, callback, thisObject) {
                var msg = new client.Message();
                msg.command = cmd;
                msg.param = param;
                msg.thisObject = thisObject;
                msg.callback = callback;
                msg.useText = false;
                this._send(msg);
                return msg;
            };
            TaurusClient.prototype.sendText = function (cmd, text, callback, thisObject) {
                var msg = new client.Message();
                msg.useText = true;
                msg.command = cmd;
                msg.textParam = text;
                msg.thisObject = thisObject;
                msg.callback = callback;
                msg.useText = true;
                this._send(msg);
                return msg;
            };
            TaurusClient.prototype.sendData = function (msg) {
                this._scoket.write(msg);
            };
            TaurusClient.prototype.clearResponse = function () {
                this._responseMap = {};
            };
            TaurusClient.prototype.getId = function () {
                return this._id;
            };
            TaurusClient.prototype.getCurrentIp = function () {
                return this._currentIp;
            };
            TaurusClient.prototype.getGameID = function () {
                return this._gameId;
            };
            TaurusClient.prototype.isConnected = function () {
                return this._connect;
            };
            TaurusClient.prototype.getProtocol = function () {
                return this._scoket.getProtocol();
            };
            TaurusClient.prototype.getAveragePingTime = function () {
                return this._scoket.getAveragePingTime();
            };
            TaurusClient.prototype.getSession = function () {
                return this._scoket.getSession();
            };
            TaurusClient.prototype.setSession = function (session) {
                this._scoket.setSession(session);
            };
            TaurusClient._tempID = 0;
            return TaurusClient;
        }());
        client.TaurusClient = TaurusClient;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var TArray = (function () {
            function TArray() {
                this.dataHolder = [];
            }
            TArray.newInstance = function () {
                return new TArray();
            };
            TArray.newFromBinaryData = function (bytes) {
                return client.TDataSerializer.me().binary2array(bytes);
            };
            TArray.newFromJson = function (json) {
                return client.TDataSerializer.me().json2array(json);
            };
            TArray.prototype.getBool = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getByte = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getByteArray = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.get = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper;
            };
            TArray.prototype.getDouble = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getFloat = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getInt = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getLong = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getTArray = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getTObject = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getShort = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.getString = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return null;
                }
                return wrapper.data;
            };
            TArray.prototype.isNull = function (index) {
                var wrapper = this.dataHolder[index];
                if (wrapper == null) {
                    return false;
                }
                return wrapper.type == 0;
            };
            TArray.prototype.addObject = function (value, typeId) {
                this.dataHolder.push(new client.TDataWrapper(typeId, value));
            };
            TArray.prototype.add = function (val) {
                this.dataHolder.push(val);
            };
            TArray.prototype.addBool = function (val) {
                this.addObject(val, 1);
            };
            TArray.prototype.addByte = function (val) {
                this.addObject(val, 2);
            };
            TArray.prototype.addByteArray = function (val) {
                this.addObject(val, 9);
            };
            TArray.prototype.addDouble = function (val) {
                this.addObject(val, 7);
            };
            TArray.prototype.addFloat = function (val) {
                this.addObject(val, 6);
            };
            TArray.prototype.addInt = function (val) {
                this.addObject(val, 4);
            };
            TArray.prototype.addLong = function (val) {
                this.addObject(val, 5);
            };
            TArray.prototype.addNull = function () {
                this.dataHolder.push(new client.TDataWrapper(0, null));
            };
            TArray.prototype.addTArray = function (val) {
                this.addObject(val, 10);
            };
            TArray.prototype.addTObject = function (val) {
                this.addObject(val, 11);
            };
            TArray.prototype.addShort = function (val) {
                this.addObject(val, 3);
            };
            TArray.prototype.addString = function (val) {
                this.addObject(val, 8);
            };
            TArray.prototype.size = function () {
                return this.dataHolder.length;
            };
            TArray.prototype.toBinary = function () {
                return client.TDataSerializer.me().array2binary(this);
            };
            TArray.prototype.toJson = function () {
                return client.TDataSerializer.me().array2json(this);
            };
            return TArray;
        }());
        client.TArray = TArray;
        var TArrayLite = (function (_super) {
            __extends(TArrayLite, _super);
            function TArrayLite() {
                return _super.call(this) || this;
            }
            TArrayLite.prototype.getByte = function (index) {
                var d = _super.prototype.getDouble.call(this, index);
                return d;
            };
            TArrayLite.prototype.getShort = function (index) {
                var d = _super.prototype.getDouble.call(this, index);
                return d;
            };
            TArrayLite.prototype.getFloat = function (index) {
                var d = _super.prototype.getDouble.call(this, index);
                return d;
            };
            TArrayLite.prototype.getLong = function (index) {
                var d = _super.prototype.getDouble.call(this, index);
                return d;
            };
            TArrayLite.prototype.getInt = function (index) {
                var d = _super.prototype.getDouble.call(this, index);
                return d;
            };
            return TArrayLite;
        }(TArray));
        client.TArrayLite = TArrayLite;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var TDataWrapper = (function () {
            function TDataWrapper(tp, data) {
                this.type = tp;
                this.data = data;
            }
            return TDataWrapper;
        }());
        client.TDataWrapper = TDataWrapper;
        var TDataSerializer = (function () {
            function TDataSerializer() {
            }
            TDataSerializer.me = function () {
                if (TDataSerializer.instance == null) {
                    TDataSerializer.instance = new TDataSerializer();
                }
                return TDataSerializer.instance;
            };
            TDataSerializer.prototype.array2binary = function (array) {
                var buffer = new client.ByteArray();
                buffer.writeByte(10);
                buffer.writeShort(array.size());
                return this.arr2bin(array, buffer);
            };
            TDataSerializer.prototype.object2binary = function (obj) {
                var buffer = new client.ByteArray();
                buffer.writeByte(11);
                buffer.writeShort(obj.size());
                return this.obj2bin(obj, buffer);
            };
            TDataSerializer.prototype.binary2array = function (data) {
                if (data.length < 3) {
                    throw Error("Can't decode an Array. Byte data is insufficient. Size: " + data.length + " byte(s)");
                }
                data.position = 0;
                return this.decodeTArray(data);
            };
            TDataSerializer.prototype.binary2object = function (data) {
                if (data.length < 3) {
                    throw "Can't decode an Object. Byte data is insufficient. Size: " + data.length + " byte(s)";
                }
                data.position = 0;
                return this.decodeTObject(data);
            };
            TDataSerializer.prototype.json2object = function (jsonStr) {
                if (jsonStr.length < 2) {
                    throw "Can't decode Object. JSON String is too short. Len: " + jsonStr.length;
                }
                var o = JSON.parse(jsonStr);
                return this.decodeTObject_json(o);
            };
            TDataSerializer.prototype.json2array = function (jsonStr) {
                if (jsonStr.length < 2) {
                    throw "Can't decode Object. JSON String is too short. Len: " + jsonStr.length;
                }
                var jsa = JSON.parse(jsonStr);
                return this.decodeTArray_json(jsa);
            };
            TDataSerializer.prototype.object2json = function (obj) {
                var map = {};
                this.flattenObject(map, obj);
                return JSON.stringify(map);
            };
            TDataSerializer.prototype.array2json = function (array) {
                var list = [];
                this.flattenArray(list, array);
                return JSON.stringify(array);
            };
            TDataSerializer.prototype.addData = function (buffer, newData) {
                buffer.writeBytes(newData.bytes);
                return buffer;
            };
            TDataSerializer.prototype.arr2bin = function (array, buffer) {
                for (var i = 0; i < array.size(); i++) {
                    var wrapped = array.get(i);
                    buffer = this.encodeObject(buffer, wrapped.type, wrapped.data);
                }
                return buffer;
            };
            TDataSerializer.prototype.binDecode_BOOL = function (buffer) {
                return new TDataWrapper(1, buffer.readBoolean());
            };
            TDataSerializer.prototype.binDecode_BYTE = function (buffer) {
                return new TDataWrapper(2, buffer.readByte());
            };
            TDataSerializer.prototype.binDecode_BYTE_ARRAY = function (buffer) {
                var count = buffer.readInt();
                if (count < 0) {
                    throw "Array negative size: " + count;
                }
                return new TDataWrapper(9, buffer.readBytes(count));
            };
            TDataSerializer.prototype.binDecode_DOUBLE = function (buffer) {
                return new TDataWrapper(7, buffer.readDouble());
            };
            TDataSerializer.prototype.binDecode_FLOAT = function (buffer) {
                return new TDataWrapper(6, buffer.readFloat());
            };
            TDataSerializer.prototype.binDecode_INT = function (buffer) {
                return new TDataWrapper(4, buffer.readInt());
            };
            TDataSerializer.prototype.binDecode_LONG = function (buffer) {
                return new TDataWrapper(5, buffer.readLong());
            };
            TDataSerializer.prototype.binDecode_NULL = function (buffer) {
                return new TDataWrapper(0, null);
            };
            TDataSerializer.prototype.binDecode_SHORT = function (buffer) {
                return new TDataWrapper(3, buffer.readShort());
            };
            TDataSerializer.prototype.binDecode_UTF_STRING = function (buffer) {
                return new TDataWrapper(8, buffer.readString());
            };
            TDataSerializer.prototype.binEncode_BOOL = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(1);
                newData.writeBoolean(val);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_BYTE_ARRAY = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(9);
                newData.writeInt(val.length);
                newData.writeBytes(val, 0, val.length);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_BYTE = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(2);
                newData.writeByte(val);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_SHORT = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(3);
                newData.writeShort(val);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_DOUBLE = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(7);
                newData.writeDouble(val);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_FLOAT = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(6);
                newData.writeFloat(val);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_INT = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(4);
                newData.writeInt(val);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_LONG = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(5);
                newData.writeLong(val);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_NULL = function (buffer) {
                var newData = new client.ByteArray();
                newData.writeByte(0);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.binEncode_STRING = function (buffer, val) {
                var newData = new client.ByteArray();
                newData.writeByte(8);
                newData.writeString(val);
                return this.addData(buffer, newData);
            };
            TDataSerializer.prototype.decodeObject = function (buffer) {
                var type = buffer.readByte();
                switch (type) {
                    case 0:
                        return this.binDecode_NULL(buffer);
                    case 1:
                        return this.binDecode_BOOL(buffer);
                    case 2:
                        return this.binDecode_BYTE(buffer);
                    case 9:
                        return this.binDecode_BYTE_ARRAY(buffer);
                    case 3:
                        return this.binDecode_SHORT(buffer);
                    case 4:
                        return this.binDecode_INT(buffer);
                    case 5:
                        return this.binDecode_LONG(buffer);
                    case 6:
                        return this.binDecode_FLOAT(buffer);
                    case 7:
                        return this.binDecode_DOUBLE(buffer);
                    case 8:
                        return this.binDecode_UTF_STRING(buffer);
                    case 10:
                        buffer.position--;
                        return new TDataWrapper(10, this.decodeTArray(buffer));
                }
                if (type != 11) {
                    throw "Unknow DataType ID: " + type;
                }
                buffer.position--;
                var mpObj = this.decodeTObject(buffer);
                return new TDataWrapper(11, mpObj);
            };
            TDataSerializer.prototype.decodeTArray = function (buffer) {
                var array = client.TArray.newInstance();
                var type = buffer.readByte();
                if (type != 10) {
                    throw "Invalid DataType. Expected: " + 10 + ", found: " + type;
                }
                var num = buffer.readShort();
                if (num < 0) {
                    throw "Can't decode Array. Size is negative: " + num;
                }
                for (var i = 0; i < num; i++) {
                    var val = this.decodeObject(buffer);
                    if (val == null) {
                        throw "Could not decode Array item at index: " + i;
                    }
                    array.add(val);
                }
                return array;
            };
            TDataSerializer.prototype.decodeTObject_json = function (jso) {
                var object = new client.TObjectLite();
                for (var key in jso) {
                    var value = jso[key];
                    var decodedObject = this.decodeJsonObject(value);
                    if (decodedObject != null)
                        object.put(key, decodedObject);
                    else {
                        throw "(json2tobj) Could not decode value for key: " + key;
                    }
                }
                return object;
            };
            TDataSerializer.prototype.decodeTArray_json = function (jsa) {
                var array = new client.TArrayLite();
                for (var _i = 0, jsa_1 = jsa; _i < jsa_1.length; _i++) {
                    var value = jsa_1[_i];
                    var decodedObject = this.decodeJsonObject(value);
                    if (decodedObject != null)
                        array.add(decodedObject);
                    else {
                        throw "(json2tobj) Could not decode value for : " + value;
                    }
                }
                return array;
            };
            TDataSerializer.prototype.decodeJsonObject = function (o) {
                if ((o.constructor == Number)) {
                    return new TDataWrapper(7, o);
                }
                if ((o.constructor == Boolean)) {
                    return new TDataWrapper(1, o);
                }
                if ((o.constructor == String)) {
                    return new TDataWrapper(8, o);
                }
                if ((o.constructor == Object)) {
                    return new TDataWrapper(11, this.decodeTObject_json(o));
                }
                if ((o.constructor == Array)) {
                    return new TDataWrapper(10, this.decodeTArray_json(o));
                }
                throw "Unknown DataType! " + (o == null ? "null" : o.constructor);
            };
            TDataSerializer.prototype.decodeTObject = function (buffer) {
                var obj2 = client.TObject.newInstance();
                var num = buffer.readByte();
                if (num != 11) {
                    throw "Invalid DataType. Expected: " + 11 + ", found: " + num;
                }
                var num2 = buffer.readShort();
                if (num2 < 0) {
                    throw "Can't decode Object. Size is negative: " + num2;
                }
                for (var i = 0; i < num2; i++) {
                    var key = buffer.readStringShort();
                    var val = this.decodeObject(buffer);
                    if (val == null) {
                        throw "Could not decode value for Object with key: " + key;
                    }
                    obj2.put(key, val);
                }
                return obj2;
            };
            TDataSerializer.prototype.flattenObject = function (map, obj) {
                var keys = obj.getKeys();
                for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
                    var key = keys_1[_i];
                    var value = obj.get(key);
                    if (value.type == 11) {
                        var newMap = {};
                        map[key] = newMap;
                        this.flattenObject(newMap, value.data);
                    }
                    else if (value.type == 10) {
                        var newList = [];
                        map[key] = newList;
                        this.flattenArray(newList, value.data);
                    }
                    else {
                        map[key] = value.data;
                    }
                }
            };
            TDataSerializer.prototype.flattenArray = function (array, tarray) {
                for (var i = 0; i < tarray.size(); ++i) {
                    var value = tarray.get(i);
                    if (value.type == 11) {
                        var newMap = {};
                        array.push(newMap);
                        this.flattenObject(newMap, value.data);
                    }
                    else if (value.type == 10) {
                        var newList = [];
                        array.push(newList);
                        this.flattenArray(newList, value.data);
                    }
                    else {
                        array.push(value.data);
                    }
                }
            };
            TDataSerializer.prototype.encodeObject = function (buffer, typeId, data) {
                switch (typeId) {
                    case 0:
                        buffer = this.binEncode_NULL(buffer);
                        return buffer;
                    case 1:
                        buffer = this.binEncode_BOOL(buffer, data);
                        return buffer;
                    case 2:
                        buffer = this.binEncode_BYTE(buffer, data);
                        return buffer;
                    case 3:
                        buffer = this.binEncode_SHORT(buffer, data);
                        return buffer;
                    case 4:
                        buffer = this.binEncode_INT(buffer, data);
                        return buffer;
                    case 5:
                        buffer = this.binEncode_LONG(buffer, data);
                        return buffer;
                    case 6:
                        buffer = this.binEncode_FLOAT(buffer, data);
                        return buffer;
                    case 7:
                        buffer = this.binEncode_DOUBLE(buffer, data);
                        return buffer;
                    case 8:
                        buffer = this.binEncode_STRING(buffer, data);
                        return buffer;
                    case 10:
                        buffer = this.addData(buffer, this.array2binary(data));
                        return buffer;
                    case 9:
                        buffer = this.binEncode_BYTE_ARRAY(buffer, data);
                        return buffer;
                    case 11:
                        buffer = this.addData(buffer, this.object2binary(data));
                        return buffer;
                }
                throw "Unrecognized type in Object serialization: " + typeId;
            };
            TDataSerializer.prototype.obj2bin = function (obj, buffer) {
                var _this = this;
                obj.getKeys().forEach(function (str) {
                    var data = obj.get(str);
                    buffer.writeStringShort(str);
                    buffer = _this.encodeObject(buffer, data.type, data.data);
                });
                return buffer;
            };
            return TDataSerializer;
        }());
        client.TDataSerializer = TDataSerializer;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var TObject = (function () {
            function TObject() {
                this.dataHolder = {};
            }
            TObject.newInstance = function () {
                return new TObject();
            };
            TObject.newFromBinaryData = function (bytes) {
                return client.TDataSerializer.me().binary2object(bytes);
            };
            TObject.newFromJson = function (json) {
                return client.TDataSerializer.me().json2object(json);
            };
            TObject.prototype.containsKey = function (key) {
                if (this.dataHolder[key])
                    return true;
                return false;
            };
            TObject.prototype.getBool = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getByte = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getByteArray = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.get = function (key) {
                return this.dataHolder[key];
            };
            TObject.prototype.getDouble = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getFloat = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getInt = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getKeys = function () {
                return Object.keys(this.dataHolder);
            };
            TObject.prototype.getLong = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getTArray = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getTObject = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getShort = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.getString = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return null;
                return o.data;
            };
            TObject.prototype.isNull = function (key) {
                var o = this.dataHolder[key];
                if (o == null)
                    return false;
                return o.type == 0;
            };
            TObject.prototype.put = function (key, val) {
                this.putObj(key, val, null);
            };
            TObject.prototype.putObj = function (key, value, typeId) {
                if (key == null) {
                    throw "TObject requires a non-null key for a 'put' operation!";
                }
                if (key.length > 255) {
                    throw "TObject keys must be less than 255 characters!";
                }
                if (value == null) {
                    throw "TObject requires a non-null value! If you need to add a null use the putNull() method.";
                }
                if (value instanceof client.TDataWrapper)
                    this.dataHolder[key] = value;
                else
                    this.dataHolder[key] = new client.TDataWrapper(typeId, value);
            };
            TObject.prototype.putBool = function (key, val) {
                this.putObj(key, val, 1);
            };
            TObject.prototype.putByte = function (key, val) {
                this.putObj(key, val, 2);
            };
            TObject.prototype.putByteArray = function (key, val) {
                this.putObj(key, val, 9);
            };
            TObject.prototype.putDouble = function (key, val) {
                this.putObj(key, val, 7);
            };
            TObject.prototype.putFloat = function (key, val) {
                this.putObj(key, val, 6);
            };
            TObject.prototype.putInt = function (key, val) {
                this.putObj(key, val, 4);
            };
            TObject.prototype.putLong = function (key, val) {
                this.putObj(key, val, 5);
            };
            TObject.prototype.putNull = function (key) {
                this.dataHolder.put(key, new client.TDataWrapper(0, null));
            };
            TObject.prototype.putTArray = function (key, val) {
                this.putObj(key, val, 10);
            };
            TObject.prototype.putTObject = function (key, val) {
                this.putObj(key, val, 11);
            };
            TObject.prototype.putShort = function (key, val) {
                this.putObj(key, val, 3);
            };
            TObject.prototype.putString = function (key, val) {
                this.putObj(key, val, 8);
            };
            TObject.prototype.del = function (key) {
                delete this.dataHolder[key];
            };
            TObject.prototype.size = function () {
                return Object.keys(this.dataHolder).length;
            };
            TObject.prototype.toBinary = function () {
                return client.TDataSerializer.me().object2binary(this);
            };
            TObject.prototype.toJson = function () {
                return client.TDataSerializer.me().object2json(this);
            };
            return TObject;
        }());
        client.TObject = TObject;
        var TObjectLite = (function (_super) {
            __extends(TObjectLite, _super);
            function TObjectLite() {
                return _super.call(this) || this;
            }
            TObjectLite.prototype.getByte = function (key) {
                var d = _super.prototype.getDouble.call(this, key);
                return d;
            };
            TObjectLite.prototype.getShort = function (key) {
                var d = _super.prototype.getDouble.call(this, key);
                return d;
            };
            TObjectLite.prototype.getFloat = function (key) {
                var d = _super.prototype.getDouble.call(this, key);
                return d;
            };
            TObjectLite.prototype.getLong = function (key) {
                var d = _super.prototype.getDouble.call(this, key);
                return d;
            };
            TObjectLite.prototype.getInt = function (key) {
                var d = _super.prototype.getDouble.call(this, key);
                return d;
            };
            return TObjectLite;
        }(TObject));
        client.TObjectLite = TObjectLite;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var Event = (function () {
            function Event(name, source) {
                if (source === void 0) { source = null; }
                this.target = source;
                this.name = name;
            }
            Event.prototype.getTarget = function () {
                return this.target;
            };
            Event.prototype.getName = function () {
                return this.name;
            };
            Event.prototype.setTarget = function (target) {
                this.target = target;
            };
            Event.prototype.setName = function (name) {
                this.name = name;
            };
            Event.prototype.getParameter = function (key) {
                return this.paramMap[key];
            };
            Event.prototype.setParameter = function (key, value) {
                if (this.paramMap == null) {
                    this.paramMap = {};
                }
                this.paramMap[key] = value;
            };
            Event.prototype.toString = function () {
                return "Event { Name:" + name + ", Source: " + this.target + ", Params: " + this.paramMap + " }";
            };
            return Event;
        }());
        client.Event = Event;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var EventDispatcher = (function () {
            function EventDispatcher() {
                this.listenersByEvent = {};
            }
            EventDispatcher.prototype.addEventListener = function (eventName, listener, thisObject) {
                var listeners = this.listenersByEvent[eventName];
                if (listeners == null) {
                    listeners = [];
                    this.listenersByEvent[eventName] = listeners;
                }
                listeners.push({
                    listener: listener, thisObject: thisObject
                });
            };
            EventDispatcher.prototype.removeEventListener = function (eventName, listener, thisObject) {
                var listeners = this.listenersByEvent[eventName];
                if (listeners) {
                    for (var i = 0; i < listeners.length; i++) {
                        var tem = listeners[i];
                        if (tem.listener === listener && tem.thisObject == thisObject) {
                            listeners.splice(i, 1);
                            break;
                        }
                    }
                }
            };
            EventDispatcher.prototype.removeAllListener = function () {
                this.listenersByEvent = {};
            };
            EventDispatcher.prototype.dispatchEvent = function (event) {
                var listeners = this.listenersByEvent[event.name];
                if (listeners) {
                    for (var i = 0; i < listeners.length; i++) {
                        var tem = listeners[i];
                        tem.listener.call(tem.thisObject, event);
                    }
                }
            };
            return EventDispatcher;
        }());
        client.EventDispatcher = EventDispatcher;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var IOHandler = (function () {
            function IOHandler(engine) {
                this._engine = engine;
            }
            IOHandler.prototype.onDataRead = function (data) {
                var compressed = data.readByte() > 0;
                var bytes = data.readBytes();
                if (compressed) {
                    bytes.uncompress();
                }
                var requestObject = client.TObject.newFromBinaryData(bytes);
                var packet = new client.Packet();
                if (requestObject.isNull(IOHandler.ACTION_ID)) {
                    throw "Request rejected: No Action ID in request!";
                }
                packet.actionID = requestObject.getByte(IOHandler.ACTION_ID);
                packet.parameters = requestObject.getTObject(IOHandler.PARAM_ID);
                this._engine._controller.handlePacket(packet);
            };
            IOHandler.prototype.onDataWrite = function (packet) {
                var obj2 = client.TObject.newInstance();
                obj2.putByte(IOHandler.ACTION_ID, packet.actionID);
                obj2.putTObject(IOHandler.PARAM_ID, packet.parameters);
                var array2 = obj2.toBinary();
                var compression = array2.length > this._engine.protocolCompression;
                if (compression) {
                    array2.compress();
                }
                var binData = new client.ByteArray();
                binData.writeByte((compression ? 1 : 0));
                binData.writeBytes(array2.bytes);
                if (this._engine._socket.readyState == WebSocket.OPEN) {
                    this._engine._socket.send(binData.bytes);
                }
            };
            IOHandler.ACTION_ID = "a";
            IOHandler.PARAM_ID = "p";
            return IOHandler;
        }());
        client.IOHandler = IOHandler;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var LagMonitor = (function () {
            function LagMonitor(engine, interval, queueSize) {
                if (interval < 1) {
                    interval = 1;
                }
                this._engine = engine;
                this._valueQueue = [];
                this._write_queue = [];
                this._queueSize = queueSize;
                this._interval = interval * 1000;
                this._averagePingTime = 0;
            }
            LagMonitor.prototype.fnPingPong = function () {
                var item = 0;
                if (this._write_queue.length > 0) {
                    var w_time = this._write_queue.pop();
                    item = new Date().getTime() - w_time;
                }
                if (this._valueQueue.length >= this._queueSize) {
                    this._valueQueue.splice(0, 1);
                }
                this._valueQueue.push(item);
                if (this._valueQueue.length == 0) {
                    this._averagePingTime = 0;
                }
                var num = 0;
                for (var i = 0; i < this._valueQueue.length; ++i) {
                    num += this._valueQueue[i];
                }
                this._averagePingTime = Math.floor(num / this._valueQueue.length);
            };
            LagMonitor.prototype.start = function () {
                if (!this.isRunning()) {
                    var self = this;
                    self._run = true;
                    self._engine._controller.sendPingPong();
                    this._pollTimer = setInterval(function () {
                        self._engine._controller.sendPingPong();
                        self._write_queue.push(new Date().getTime());
                    }, this._interval);
                }
            };
            LagMonitor.prototype.stop = function () {
                if (this.isRunning()) {
                    this._run = false;
                    clearInterval(this._pollTimer);
                }
            };
            LagMonitor.prototype.destroy = function () {
                this.stop();
                this._engine = null;
            };
            LagMonitor.prototype.getAveragePingTime = function () {
                return this._averagePingTime;
            };
            LagMonitor.prototype.isRunning = function () {
                return this._run;
            };
            return LagMonitor;
        }());
        client.LagMonitor = LagMonitor;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var Packet = (function () {
            function Packet() {
            }
            return Packet;
        }());
        client.Packet = Packet;
        var Callback = (function () {
            function Callback(_thisObject, _func) {
                this.thisObject = _thisObject;
                this.func = _func;
            }
            return Callback;
        }());
        var SocketEngine = (function () {
            function SocketEngine(secure) {
                this.protocolCompression = 512;
                this._state = 0;
                this._controller = new client.SystemController(this);
                this._packetHandler = new client.IOHandler(this);
                this._lagMonitor = new client.LagMonitor(this, client.NetManager.TIMEOUT_TIME, 10);
                this._secure = secure;
            }
            SocketEngine.prototype.connect = function (ip, game) {
                var self = this;
                if (this._state != 0) {
                    client.log.error("Calling connect when the socket is not disconnected");
                    return false;
                }
                this._state = 1;
                this._socket = new WebSocket(this._secure ? "wss" : "ws" + "://" + ip + "/websocket");
                this._socket.binaryType = "arraybuffer";
                this._socket.onopen = function (ev) {
                    self._controller.sendHandshake();
                    self._state = 2;
                };
                this._socket.onmessage = function (ev) {
                    if (ev.data instanceof ArrayBuffer) {
                        var bytes = new client.ByteArray(ev.data);
                        self._packetHandler.onDataRead(bytes);
                    }
                };
                this._socket.onclose = function (ev) {
                    if (client.NetManager.debug_print) {
                        client.log.debug("onclose: wasClean ={0}, code={1}, reason={2}", ev.wasClean, ev.code, ev.reason);
                    }
                    if (self._state != 1) {
                        if (ev.code == 1000) {
                            self.onStatusChanged(client.SocketCode.Disconnect);
                        }
                        else if (ev.code == 1001) {
                            self.onStatusChanged(client.SocketCode.DisconnectByServer);
                        }
                        else if (1006 == ev.code) {
                            self.onStatusChanged(client.SocketCode.TimeoutDisconnect);
                        }
                        else if (ev.code > 1000) {
                            self.onStatusChanged(client.SocketCode.ExceptionOnReceive);
                        }
                    }
                };
                this._socket.onerror = function (ev) {
                    self._onError(ev);
                };
            };
            SocketEngine.prototype._onError = function (ev) {
                client.log.error("Connection error:", ev);
                if (this._state == 1) {
                    this.onStatusChanged(client.SocketCode.ExceptionOnConnect);
                }
                else {
                    this.onStatusChanged(client.SocketCode.Exception);
                }
            };
            SocketEngine.prototype.onStatusChanged = function (statusCode) {
                if (statusCode != client.SocketCode.Connect) {
                    this.disconnect();
                }
                var cb = this._onConnect;
                cb.func.call(cb.thisObject, statusCode);
            };
            SocketEngine.prototype.onHandshake = function (packet) {
                this._sessionToken = packet.parameters.getString(client.SystemController.CONNECT_TOKE);
                this.protocolCompression = packet.parameters.getInt(client.SystemController.CONNECT_PROT_COMPRESSION);
                var cb = this._onConnect;
                cb.func.call(cb.thisObject, client.SocketCode.Connect);
                if (this._lagMonitor != null) {
                    this._lagMonitor.start();
                }
            };
            SocketEngine.prototype.disconnect = function () {
                if (this._state == 0)
                    return false;
                if (this._lagMonitor != null)
                    this._lagMonitor.destroy();
                this._lagMonitor = null;
                this._state = 3;
                this._socket.close();
            };
            SocketEngine.prototype.write = function (msg) {
                this._controller.sendRequest(msg);
            };
            SocketEngine.prototype.getProtocol = function () {
                return client.ConnectionProtocol.WebSocket;
            };
            SocketEngine.prototype.setOnConnect = function (func, thisObject) {
                this._onConnect = new Callback(thisObject, func);
            };
            SocketEngine.prototype.setOnEvent = function (func, thisObject) {
                this._onEvent = new Callback(thisObject, func);
            };
            SocketEngine.prototype.getAveragePingTime = function () {
                return this._lagMonitor != null ? this._lagMonitor.getAveragePingTime() : 300;
            };
            SocketEngine.prototype.getSession = function () {
                return this._sessionToken;
            };
            SocketEngine.prototype.setSession = function (session) {
                this._sessionToken = session;
            };
            return SocketEngine;
        }());
        client.SocketEngine = SocketEngine;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var SystemController = (function () {
            function SystemController(engine) {
                this._tempID = 0;
                this._handleList = [];
                this._engine = engine;
            }
            SystemController.prototype._getValidID = function () {
                return ++this._tempID;
            };
            SystemController.prototype.handlePacket = function (packet) {
                switch (packet.actionID) {
                    case SystemController.ACTION_HANDSHAKE:
                        this.fnHandshake(packet);
                        break;
                    case SystemController.ACTION_PINGPONG:
                        this.fnPingPong(packet);
                        break;
                    case SystemController.ACTION_REQUST_CMD:
                        this.fnOperationResponse(packet);
                        break;
                    case SystemController.ACTION_EVENT_CMD:
                        this.fnOperationEvent(packet);
                        break;
                }
            };
            SystemController.prototype.fnOperationResponse = function (packet) {
                var gid = packet.parameters.getInt(SystemController.REQUEST_GID);
                var result = packet.parameters.getInt(SystemController.REQUEST_RESULT);
                var tem = null;
                if (packet.parameters.containsKey(SystemController.REQUEST_PARM)) {
                    tem = packet.parameters.getTObject(SystemController.REQUEST_PARM);
                }
                var msg = null;
                var index = 0;
                var len = this._handleList.length;
                if (gid > 0) {
                    for (var i = 0; i < len; ++i) {
                        if (gid == this._handleList[i].gid) {
                            msg = this._handleList[i];
                            index = i;
                            break;
                        }
                    }
                }
                if (msg != null) {
                    if (msg.callback != null) {
                        var response = new client.MessageResponse();
                        if (result == 0) {
                            msg.param = tem;
                        }
                        response.messageData = msg;
                        response.returnCode = result;
                        msg.callback(response);
                    }
                    this._handleList.splice(index, 1);
                }
            };
            SystemController.prototype.fnOperationEvent = function (packet) {
                var cmd = packet.parameters.getString(SystemController.REQUEST_CMD);
                var tem = null;
                if (packet.parameters.containsKey(SystemController.REQUEST_PARM)) {
                    tem = packet.parameters.getTObject(SystemController.REQUEST_PARM);
                }
                this.handleEvent(cmd, tem);
            };
            SystemController.prototype.handleEvent = function (cmd, param) {
                var msg = new client.Message();
                msg.command = cmd;
                msg.param = param;
                var cb = this._engine._onEvent;
                cb.func.call(cb.thisObject, msg);
            };
            SystemController.prototype.fnHandshake = function (packet) {
                this._engine.onHandshake(packet);
            };
            SystemController.prototype.fnPingPong = function (packet) {
                this._engine._lagMonitor.fnPingPong();
            };
            SystemController.prototype.sendRequest = function (msg) {
                var packet = new client.Packet();
                packet.actionID = SystemController.ACTION_REQUST_CMD;
                var obj = client.TObject.newInstance();
                obj.putString(SystemController.REQUEST_CMD, msg.command);
                if (msg.param != null) {
                    obj.putTObject(SystemController.REQUEST_PARM, msg.param);
                }
                if (msg.callback != null) {
                    var gid = this._getValidID();
                    obj.putInt(SystemController.REQUEST_GID, gid);
                    msg.gid = gid;
                    this._handleList.push(msg);
                }
                packet.parameters = obj;
                this._engine._packetHandler.onDataWrite(packet);
            };
            SystemController.prototype.sendPingPong = function () {
                var packet = new client.Packet();
                packet.actionID = SystemController.ACTION_PINGPONG;
                packet.parameters = client.TObject.newInstance();
                this._engine._packetHandler.onDataWrite(packet);
            };
            SystemController.prototype.sendHandshake = function () {
                var packet = new client.Packet();
                packet.actionID = SystemController.ACTION_HANDSHAKE;
                packet.parameters = client.TObject.newInstance();
                this._engine._packetHandler.onDataWrite(packet);
            };
            SystemController.CONNECT_TOKE = "$t";
            SystemController.CONNECT_PROT_COMPRESSION = "$pc";
            SystemController.REQUEST_CMD = "$c";
            SystemController.REQUEST_GID = "$gi";
            SystemController.REQUEST_PARM = "$p";
            SystemController.REQUEST_RESULT = "$r";
            SystemController.ACTION_HANDSHAKE = 0;
            SystemController.ACTION_PINGPONG = 1;
            SystemController.ACTION_REQUST_CMD = 2;
            SystemController.ACTION_EVENT_CMD = 3;
            return SystemController;
        }());
        client.SystemController = SystemController;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        function int64BEtoNumber(bytes, pos) {
            var sign = bytes[pos + 0] >> 7;
            var sum = 0;
            var digits = 1;
            for (var i = 0; i < 8; i++) {
                var value = bytes[pos + (7 - i)];
                sum += (sign ? value ^ 0xFF : value) * digits;
                digits *= 0x100;
            }
            return sign ? -1 - sum : sum;
        }
        function numberToInt64BE(val) {
            var result = [];
            var sign = val < 0;
            if (sign)
                val = -1 - val;
            for (var i = 0; i < 8; i++) {
                var mod = val % 0x100;
                val = (val - mod) / 0x100;
                result[7 - i] = sign ? mod ^ 0xFF : mod;
            }
            return result;
        }
        var ByteArray = (function () {
            function ByteArray(buffer, bufferExtSize) {
                if (bufferExtSize === void 0) { bufferExtSize = 0; }
                this.littleEndian = false;
                this.bufferExtSize = 0;
                this.EOF_byte = -1;
                this.EOF_code_point = -1;
                if (bufferExtSize < 0) {
                    bufferExtSize = 0;
                }
                this.bufferExtSize = bufferExtSize;
                var bytes, wpos = 0;
                if (buffer) {
                    var uint8 = void 0;
                    if (buffer instanceof Uint8Array) {
                        uint8 = buffer;
                        wpos = buffer.length;
                    }
                    else {
                        wpos = buffer.byteLength;
                        uint8 = new Uint8Array(buffer);
                    }
                    if (bufferExtSize == 0) {
                        bytes = new Uint8Array(wpos);
                    }
                    else {
                        var multi = (wpos / bufferExtSize | 0) + 1;
                        bytes = new Uint8Array(multi * bufferExtSize);
                    }
                    bytes.set(uint8);
                }
                else {
                    bytes = new Uint8Array(bufferExtSize);
                }
                this.write_position = wpos;
                this._position = 0;
                this._bytes = bytes;
                this.data = new DataView(bytes.buffer);
            }
            Object.defineProperty(ByteArray.prototype, "readAvailable", {
                get: function () {
                    return this.write_position - this._position;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(ByteArray.prototype, "buffer", {
                get: function () {
                    return this.data.buffer.slice(0, this.write_position);
                },
                set: function (value) {
                    var wpos = value.byteLength;
                    var uint8 = new Uint8Array(value);
                    var bufferExtSize = this.bufferExtSize;
                    var bytes;
                    if (bufferExtSize == 0) {
                        bytes = new Uint8Array(wpos);
                    }
                    else {
                        var multi = (wpos / bufferExtSize | 0) + 1;
                        bytes = new Uint8Array(multi * bufferExtSize);
                    }
                    bytes.set(uint8);
                    this.write_position = wpos;
                    this._bytes = bytes;
                    this.data = new DataView(bytes.buffer);
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(ByteArray.prototype, "rawBuffer", {
                get: function () {
                    return this.data.buffer;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(ByteArray.prototype, "bytes", {
                get: function () {
                    return this._bytes;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(ByteArray.prototype, "dataView", {
                get: function () {
                    return this.data;
                },
                set: function (value) {
                    this.buffer = value.buffer;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(ByteArray.prototype, "position", {
                get: function () {
                    return this._position;
                },
                set: function (value) {
                    this._position = value;
                    if (value > this.write_position) {
                        this.write_position = value;
                    }
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(ByteArray.prototype, "length", {
                get: function () {
                    return this.write_position;
                },
                set: function (value) {
                    this.write_position = value;
                    if (this.data.byteLength > value) {
                        this._position = value;
                    }
                    this._validateBuffer(value);
                },
                enumerable: true,
                configurable: true
            });
            ByteArray.prototype._validateBuffer = function (value) {
                if (this.data.byteLength < value) {
                    var be = this.bufferExtSize;
                    var tmp = void 0;
                    if (be == 0) {
                        tmp = new Uint8Array(value);
                    }
                    else {
                        var nLen = ((value / be >> 0) + 1) * be;
                        tmp = new Uint8Array(nLen);
                    }
                    tmp.set(this._bytes);
                    this._bytes = tmp;
                    this.data = new DataView(tmp.buffer);
                }
            };
            Object.defineProperty(ByteArray.prototype, "bytesAvailable", {
                get: function () {
                    return this.data.byteLength - this._position;
                },
                enumerable: true,
                configurable: true
            });
            ByteArray.prototype.clear = function () {
                var buffer = new ArrayBuffer(this.bufferExtSize);
                this.data = new DataView(buffer);
                this._bytes = new Uint8Array(buffer);
                this._position = 0;
                this.write_position = 0;
            };
            ByteArray.prototype.readBoolean = function () {
                if (this.validate(1))
                    return !!this._bytes[this.position++];
            };
            ByteArray.prototype.readByte = function () {
                if (this.validate(1))
                    return this.data.getInt8(this.position++);
            };
            ByteArray.prototype.readBytes = function (length) {
                if (length === void 0) { length = 0; }
                var pos = this._position;
                var available = this.write_position - pos;
                if (available < 0) {
                    client.log.error("1025");
                    return;
                }
                if (length == 0) {
                    length = available;
                }
                else if (length > available) {
                    client.log.error("1025");
                    return;
                }
                var bytes = new Uint8Array(length);
                bytes.set(this._bytes.subarray(pos, pos + length), 0);
                this.position += length;
                return new ByteArray(bytes);
            };
            ByteArray.prototype.uncompress = function () {
                var inflate = new Zlib.Inflate(this._bytes);
                var inbuffer = inflate.decompress();
                this._bytes = inbuffer;
                this.write_position = inbuffer.length;
                this._position = 0;
                this.data = new DataView(this._bytes.buffer);
            };
            ByteArray.prototype.compress = function () {
                var deflate = new Zlib.Deflate(this._bytes);
                var inbuffer = deflate.compress();
                this._bytes = inbuffer;
                this.write_position = inbuffer.length;
                this._position = 0;
                this.data = new DataView(this._bytes.buffer);
            };
            ByteArray.prototype.readDouble = function () {
                if (this.validate(8)) {
                    var value = this.data.getFloat64(this._position, this.littleEndian);
                    this.position += 8;
                    return value;
                }
            };
            ByteArray.prototype.readFloat = function () {
                if (this.validate(4)) {
                    var value = this.data.getFloat32(this._position, this.littleEndian);
                    this.position += 4;
                    return value;
                }
            };
            ByteArray.prototype.readInt = function () {
                if (this.validate(4)) {
                    var value = this.data.getInt32(this._position, this.littleEndian);
                    this.position += 4;
                    return value;
                }
            };
            ByteArray.prototype.readLong = function () {
                if (this.validate(4)) {
                    var value = int64BEtoNumber(this.bytes, this._position);
                    this.position += 8;
                    return value;
                }
            };
            ByteArray.prototype.readShort = function () {
                if (this.validate(2)) {
                    var value = this.data.getInt16(this._position, this.littleEndian);
                    this.position += 2;
                    return value;
                }
            };
            ByteArray.prototype.readUByte = function () {
                if (this.validate(1))
                    return this._bytes[this.position++];
            };
            ByteArray.prototype.readUInt = function () {
                if (this.validate(4)) {
                    var value = this.data.getUint32(this._position, this.littleEndian);
                    this.position += 4;
                    return value;
                }
            };
            ByteArray.prototype.readUShort = function () {
                if (this.validate(2)) {
                    var value = this.data.getUint16(this._position, this.littleEndian);
                    this.position += 2;
                    return value;
                }
            };
            ByteArray.prototype.readString = function () {
                var length = this.readUInt();
                if (length > 0) {
                    return this._readUTFBytes(length);
                }
                else {
                    return "";
                }
            };
            ByteArray.prototype.readStringShort = function () {
                var length = this.readUShort();
                if (length > 0) {
                    return this._readUTFBytes(length);
                }
                else {
                    return "";
                }
            };
            ByteArray.prototype._readUTFBytes = function (length) {
                if (!this.validate(length)) {
                    return;
                }
                var data = this.data;
                var bytes = new Uint8Array(data.buffer, data.byteOffset + this._position, length);
                this.position += length;
                return this.decodeUTF8(bytes);
            };
            ByteArray.prototype.writeBoolean = function (value) {
                this.validateBuffer(1);
                this._bytes[this.position++] = +value;
            };
            ByteArray.prototype.writeByte = function (value) {
                this.validateBuffer(1);
                this._bytes[this.position++] = value & 0xff;
            };
            ByteArray.prototype.writeBytes = function (bytes, offset, length) {
                if (offset === void 0) { offset = 0; }
                if (length === void 0) { length = 0; }
                var writeLength;
                if (offset < 0) {
                    return;
                }
                if (length < 0) {
                    return;
                }
                else if (length == 0) {
                    writeLength = bytes.length - offset;
                }
                else {
                    writeLength = Math.min(bytes.length - offset, length);
                }
                if (writeLength > 0) {
                    this.validateBuffer(writeLength);
                    this._bytes.set(bytes.subarray(offset, offset + writeLength), this._position);
                    this.position = this._position + writeLength;
                }
            };
            ByteArray.prototype.writeLong = function (value) {
                this.validateBuffer(8);
                this._bytes.set(numberToInt64BE(value), this._position);
                this.position += 8;
            };
            ByteArray.prototype.writeDouble = function (value) {
                this.validateBuffer(8);
                this.data.setFloat64(this._position, value, this.littleEndian);
                this.position += 8;
            };
            ByteArray.prototype.writeFloat = function (value) {
                this.validateBuffer(4);
                this.data.setFloat32(this._position, value, this.littleEndian);
                this.position += 4;
            };
            ByteArray.prototype.writeInt = function (value) {
                this.validateBuffer(4);
                this.data.setInt32(this._position, value, this.littleEndian);
                this.position += 4;
            };
            ByteArray.prototype.writeShort = function (value) {
                this.validateBuffer(2);
                this.data.setInt16(this._position, value, this.littleEndian);
                this.position += 2;
            };
            ByteArray.prototype.writeUInt = function (value) {
                this.validateBuffer(4);
                this.data.setUint32(this._position, value, this.littleEndian);
                this.position += 4;
            };
            ByteArray.prototype.writeUShort = function (value) {
                this.validateBuffer(2);
                this.data.setUint16(this._position, value, this.littleEndian);
                this.position += 2;
            };
            ByteArray.prototype.writeString = function (value) {
                var utf8bytes = this.encodeUTF8(value);
                var length = utf8bytes.length;
                this.validateBuffer(4 + length);
                this.data.setUint32(this._position, length, this.littleEndian);
                this.position += 4;
                this._writeUint8Array(utf8bytes, false);
            };
            ByteArray.prototype.writeStringShort = function (value) {
                var utf8bytes = this.encodeUTF8(value);
                var length = utf8bytes.length;
                this.validateBuffer(2 + length);
                this.data.setUint16(this._position, length, this.littleEndian);
                this.position += 2;
                this._writeUint8Array(utf8bytes, false);
            };
            ByteArray.prototype.toString = function () {
                return "[ByteArray] length:" + this.length + ", bytesAvailable:" + this.bytesAvailable;
            };
            ByteArray.prototype._writeUint8Array = function (bytes, validateBuffer) {
                if (validateBuffer === void 0) { validateBuffer = true; }
                var pos = this._position;
                var npos = pos + bytes.length;
                if (validateBuffer) {
                    this.validateBuffer(npos);
                }
                this.bytes.set(bytes, pos);
                this.position = npos;
            };
            ByteArray.prototype.validate = function (len) {
                var bl = this._bytes.length;
                if (bl > 0 && this._position + len <= bl) {
                    return true;
                }
            };
            ByteArray.prototype.validateBuffer = function (len) {
                this.write_position = len > this.write_position ? len : this.write_position;
                len += this._position;
                this._validateBuffer(len);
            };
            ByteArray.prototype.encodeUTF8 = function (str) {
                var pos = 0;
                var codePoints = this.stringToCodePoints(str);
                var outputBytes = [];
                while (codePoints.length > pos) {
                    var code_point = codePoints[pos++];
                    if (this.inRange(code_point, 0xD800, 0xDFFF)) {
                        client.log.error("range error!{0}", code_point);
                    }
                    else if (this.inRange(code_point, 0x0000, 0x007f)) {
                        outputBytes.push(code_point);
                    }
                    else {
                        var count = void 0, offset = void 0;
                        if (this.inRange(code_point, 0x0080, 0x07FF)) {
                            count = 1;
                            offset = 0xC0;
                        }
                        else if (this.inRange(code_point, 0x0800, 0xFFFF)) {
                            count = 2;
                            offset = 0xE0;
                        }
                        else if (this.inRange(code_point, 0x10000, 0x10FFFF)) {
                            count = 3;
                            offset = 0xF0;
                        }
                        outputBytes.push(this.div(code_point, Math.pow(64, count)) + offset);
                        while (count > 0) {
                            var temp = this.div(code_point, Math.pow(64, count - 1));
                            outputBytes.push(0x80 + (temp % 64));
                            count -= 1;
                        }
                    }
                }
                return new Uint8Array(outputBytes);
            };
            ByteArray.prototype.decodeUTF8 = function (data) {
                var fatal = false;
                var pos = 0;
                var result = "";
                var code_point;
                var utf8_code_point = 0;
                var utf8_bytes_needed = 0;
                var utf8_bytes_seen = 0;
                var utf8_lower_boundary = 0;
                while (data.length > pos) {
                    var _byte = data[pos++];
                    if (_byte == this.EOF_byte) {
                        if (utf8_bytes_needed != 0) {
                            code_point = this.decoderError(fatal);
                        }
                        else {
                            code_point = this.EOF_code_point;
                        }
                    }
                    else {
                        if (utf8_bytes_needed == 0) {
                            if (this.inRange(_byte, 0x00, 0x7F)) {
                                code_point = _byte;
                            }
                            else {
                                if (this.inRange(_byte, 0xC2, 0xDF)) {
                                    utf8_bytes_needed = 1;
                                    utf8_lower_boundary = 0x80;
                                    utf8_code_point = _byte - 0xC0;
                                }
                                else if (this.inRange(_byte, 0xE0, 0xEF)) {
                                    utf8_bytes_needed = 2;
                                    utf8_lower_boundary = 0x800;
                                    utf8_code_point = _byte - 0xE0;
                                }
                                else if (this.inRange(_byte, 0xF0, 0xF4)) {
                                    utf8_bytes_needed = 3;
                                    utf8_lower_boundary = 0x10000;
                                    utf8_code_point = _byte - 0xF0;
                                }
                                else {
                                    this.decoderError(fatal);
                                }
                                utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed);
                                code_point = null;
                            }
                        }
                        else if (!this.inRange(_byte, 0x80, 0xBF)) {
                            utf8_code_point = 0;
                            utf8_bytes_needed = 0;
                            utf8_bytes_seen = 0;
                            utf8_lower_boundary = 0;
                            pos--;
                            code_point = this.decoderError(fatal, _byte);
                        }
                        else {
                            utf8_bytes_seen += 1;
                            utf8_code_point = utf8_code_point + (_byte - 0x80) * Math.pow(64, utf8_bytes_needed - utf8_bytes_seen);
                            if (utf8_bytes_seen !== utf8_bytes_needed) {
                                code_point = null;
                            }
                            else {
                                var cp = utf8_code_point;
                                var lower_boundary = utf8_lower_boundary;
                                utf8_code_point = 0;
                                utf8_bytes_needed = 0;
                                utf8_bytes_seen = 0;
                                utf8_lower_boundary = 0;
                                if (this.inRange(cp, lower_boundary, 0x10FFFF) && !this.inRange(cp, 0xD800, 0xDFFF)) {
                                    code_point = cp;
                                }
                                else {
                                    code_point = this.decoderError(fatal, _byte);
                                }
                            }
                        }
                    }
                    if (code_point !== null && code_point !== this.EOF_code_point) {
                        if (code_point <= 0xFFFF) {
                            if (code_point > 0)
                                result += String.fromCharCode(code_point);
                        }
                        else {
                            code_point -= 0x10000;
                            result += String.fromCharCode(0xD800 + ((code_point >> 10) & 0x3ff));
                            result += String.fromCharCode(0xDC00 + (code_point & 0x3ff));
                        }
                    }
                }
                return result;
            };
            ByteArray.prototype.decoderError = function (fatal, opt_code_point) {
                return opt_code_point || 0xFFFD;
            };
            ByteArray.prototype.inRange = function (a, min, max) {
                return min <= a && a <= max;
            };
            ByteArray.prototype.div = function (n, d) {
                return Math.floor(n / d);
            };
            ByteArray.prototype.stringToCodePoints = function (string) {
                var cps = [];
                var i = 0, n = string.length;
                while (i < string.length) {
                    var c = string.charCodeAt(i);
                    if (!this.inRange(c, 0xD800, 0xDFFF)) {
                        cps.push(c);
                    }
                    else if (this.inRange(c, 0xDC00, 0xDFFF)) {
                        cps.push(0xFFFD);
                    }
                    else {
                        if (i == n - 1) {
                            cps.push(0xFFFD);
                        }
                        else {
                            var d = string.charCodeAt(i + 1);
                            if (this.inRange(d, 0xDC00, 0xDFFF)) {
                                var a = c & 0x3FF;
                                var b = d & 0x3FF;
                                i += 1;
                                cps.push(0x10000 + (a << 10) + b);
                            }
                            else {
                                cps.push(0xFFFD);
                            }
                        }
                    }
                    i += 1;
                }
                return cps;
            };
            return ByteArray;
        }());
        client.ByteArray = ByteArray;
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
var taurus;
(function (taurus) {
    var client;
    (function (client) {
        var LoggerLevel;
        (function (LoggerLevel) {
            LoggerLevel[LoggerLevel["DEBUG"] = 0] = "DEBUG";
            LoggerLevel[LoggerLevel["INFO"] = 1] = "INFO";
            LoggerLevel[LoggerLevel["WARN"] = 2] = "WARN";
            LoggerLevel[LoggerLevel["ERROR"] = 3] = "ERROR";
            LoggerLevel[LoggerLevel["TRACE"] = 4] = "TRACE";
        })(LoggerLevel || (LoggerLevel = {}));
        function stringFormat(str) {
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            var result = str;
            if (args.length > 0) {
                for (var i = 0; i < args.length; i++) {
                    if (args[i] != undefined) {
                        var reg = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, args[i]);
                    }
                }
            }
            return result;
        }
        var Logger = (function () {
            function Logger() {
            }
            Logger.prototype._print = function (level, str) {
                var date = new Date();
                var msg = stringFormat("[{0}:{1}:{2}]-> {3}", date.getHours(), date.getMinutes(), date.getMilliseconds(), str);
                if (level == LoggerLevel.WARN) {
                    console.warn(msg);
                }
                else if (level == LoggerLevel.ERROR) {
                    console.error(msg);
                }
                else {
                    console.info(msg);
                }
            };
            Logger.prototype.debug = function (msg) {
                var params = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                    params[_i - 1] = arguments[_i];
                }
                var str = msg.toString();
                if (params && params.length > 0) {
                    str = stringFormat.apply(void 0, [msg.toString()].concat(params));
                }
                this._print(LoggerLevel.DEBUG, str);
            };
            Logger.prototype.info = function (msg) {
                var params = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                    params[_i - 1] = arguments[_i];
                }
                var str = msg.toString();
                if (params && params.length > 0) {
                    str = stringFormat.apply(void 0, [str].concat(params));
                }
                this._print(LoggerLevel.INFO, str);
            };
            Logger.prototype.warn = function (msg) {
                var params = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                    params[_i - 1] = arguments[_i];
                }
                var str = msg.toString();
                if (params && params.length > 0) {
                    str = stringFormat.apply(void 0, [str].concat(params));
                }
                this._print(LoggerLevel.WARN, str);
            };
            Logger.prototype.error = function (msg) {
                var params = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                    params[_i - 1] = arguments[_i];
                }
                var str = msg.toString();
                if (params && params.length > 0) {
                    str = stringFormat.apply(void 0, [str].concat(params));
                }
                this._print(LoggerLevel.ERROR, str);
            };
            return Logger;
        }());
        client.Logger = Logger;
        client.log = new Logger();
    })(client = taurus.client || (taurus.client = {}));
})(taurus || (taurus = {}));
